<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use PHPExcel;
class Pay extends BaseModel
{
    public $timestamps = false;

    protected $table = 'pay';

    protected $guarded = [];

    public function getOne($where, $fileds = '*', $order = '')
    {
        if (!$order) {
            $order = ['pay_id' => 'desc'];
        }
        return $this->multiSelect($fileds)->multiWhere($where)->multiOrder($order)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 获取全部数据
     * @param array $where
     * @param string $fields
     * @param array $order
     * @return mixed
     */
    public function getAll($where = [], $fields = "*", $order = ['created_at' => 'desc'])
    {
        return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        return $this->_add($data);
    }


    /***
     * @param array $id
     * @param array $data
     * 更新数据
     */
    public function up($where, $data)
    {
        return $this->_updata($where, $data);
    }

    /**
     * @param $id
     * 删除数据
     */
    public function del($where)
    {
        return $this->_del($where);
    }

    public function count($where = [], $field = '*')
    {
        return $this->_count($where, $field);
    }

    /**
     * 格式化用户名
     * @param unknown $currency_id   币种id
     * @return unknown
     */
    function getCurrencynameByCurrency($currency_id){
        if(isset($currency_id)){
            if($currency_id==0){
                return "人民币";
            }
            $result = Currency::where("currency_id",$currency_id)->first();
            return $result['currency_name'];
        }else{
            return "未知钱币";
        }
    }



    /**
     * 人民币收入
     */
    public function get_money_count()
    {
        $pay_money_count = Pay::where('status','1')->sum('count');
        return $pay_money_count;
    }

    /**
     * 充值单数
     */
    public function get_pay_count()
    {
        $pay_count = Pay::where('status','1')->count();
        return $pay_count;
    }

    /**
     * 财务管理--人工充值管理列表
     */
    public function get_payByMan($request)
    {
        $status = $request['status'];
        $member_name = $request['member_name'];
        if (!empty($status) || $status == 0) {
            $where['pay.status'] = $status;
        }
        if (!empty($member_name)) {
            $where['pay.member_name'] = $member_name;
        }

        if ($status == "" && $member_name == "") {
            $result = DB::table('pay')
                ->join('member','pay.member_name','=','member.name')
                ->select('pay.*','member.email')
                ->orderBy('add_time','desc')
                ->paginate(5);
        } elseif($status == '' && !empty($member_name)){
            $result = DB::table('pay')
                ->join('member','pay.member_name','=','member.name')
                ->select('pay.*','member.email')
                ->where('pay.member_name','like',$member_name.'%')
                ->orderBy('add_time','desc')
                ->paginate(5);
        } else{
            $result = DB::table('pay')
                ->join('member','pay.member_name','=','member.name')
                ->select('pay.*','member.email')
                ->where($where)
                ->orderBy('add_time','desc')
                ->paginate(5);
        }
        return $result;
    }

    /**
     *  财务管理--人工充值管理修改操作
     */
    public function payEdit($request)
    {
        $where['pay_id'] = $request['pay_id'];
        $list = $this->getOne($where);
        if ($list['status'] !== 0 )
        {
            $res['status'] = -1;
            $res['msg'] = "请不要重复操作";
            return $res;
        }
        $all = Member::where("member_id",$list['member_id'])->get();
        foreach ($all as $k=>$v){
            $member_id = $v['member_id'];
        }
        if ($request['status'] == 1)
        {
             DB::table('pay')->where('pay_id', $where['pay_id'])->update(['status' => 1]);
           if ($list['money'] >= $this->congif['pay_reward_limit']) {
                $list['count'] = $list['count'] + $list['money'] * $this->config['pay_reward'] / 100;
        }
            //修改member表钱数
            $rs = DB::table('member')->where("member_id",$list['member_id'])->update(['rmb'=>$list['count']]);
            //添加财务日志
            DB::table('finance')->insert(['member_id' => $member_id ,'type'=> 6,'content' => '线下充值'.$list['count'],'money' => $list['count'] , 'money_type' => 1 , 'currency_id' => 0]);
            //添加信息表
              DB::table('message_all')->insert(['title' => '人工充值成功','u_id' => $member_id ,'type'=> -2,'content'=>'您申请的人工充值已成功，充值金额为'.$list['count']]);
        }
        elseif ($request['status'] == 2 )
        {
           $rs = DB::table('pay')->where('pay_id', $where['pay_id'])->update(['status' => 2]);
            //添加信息表
            DB::table('message_all')->insert(['title' => '人工充值审核未开通','u_id' => $member_id ,'type'=> -2,'content'=>'您申请的人工充值审核未通过,请重新处理']);
        }
        else
        {
            $res['status'] = 0;
            $res['msg'] = "操作有误";
            return $res;
        }
        if ($rs) {
            $res['status'] = 1;
            $res['msg'] = "修改成功";
            return $res;
        }else{
            $res['status'] = 2;
            $res['msg'] = "修改失败";
            return $res;
        }
    }

   /**
    * 表格导出
    */
    public function payExcel($request)
    {
        //时间筛选
        $result = [];
        $add_time = $request['add_time'];
        $end_time = $request['end_time'];
        $add_time = empty ($add_time)? 0:strtotime($add_time);
        $end_time = empty ($end_time)? 0:strtotime($end_time);
        $list = DB::table('pay')
            ->leftJoin('member','pay.member_name','=','member.name')
            ->where('pay.add_time','<',$end_time)
            ->where('pay.add_time','>=',$add_time)
            ->select('pay.pay_id','member.email','member.name','pay.account','pay.money','pay.count','pay.status','pay.add_time')
            ->orderBy('pay.add_time','desc')
            ->get();
        foreach ($list as $k=>$v){
            $list[$k]->status = payStatus($v->status);
            $list[$k]->add_time = date('Y-m-d H:i:s',$v->add_time);
        }
        foreach ($list as $k=>$v) {
            foreach ($v as $kk=>$vv) {
                $result[$k][$kk] = $vv;
            }
        }
        $re = Config::get();
        foreach ($re as $k=>$v) {
            $data[$v['key']] = $v['value'];
        }
        $filename= $data['name']."人工充值日志-".date('Y-m-d',time());
        $excel = new PHPExcel();
        //设置标题
       $excel->getActiveSheet()->setTitle($filename);
        //设置表头
        $excel->getActiveSheet()
                ->setCellValue('A1','订单号')
                ->setCellValue('B1','汇款人账号')
                ->setCellValue('C1','汇款人')
                ->setCellValue('D1','银行卡号')
                ->setCellValue('E1','充值钱数')
                ->setCellValue('F1','实际打款')
                ->setCellValue('G1','状态')
                ->setCellValue('H1','时间');

        //用foreach从第二行开始写数据，因为第一行是表头
        $i = 2;
        foreach($result as $val){
        $excel->getActiveSheet() ->setCellValue('A'.$i,$val['pay_id'])
                ->setCellValue('B'.$i, $val['email'])
                ->setCellValue('C'.$i, $val['name'])
                ->setCellValue('D'.$i, $val['account'])
                ->setCellValue('E'.$i, $val['money'])
                ->setCellValue('F'.$i, $val['count'])
                ->setCellValue('G'.$i, $val['status'])
                ->setCellValue('H'.$i, $val['add_time']);
            $i++;
        }
        // 设置活动单指数到第一个表,所以Excel打开这是第一个表  
        $excel->setActiveSheetIndex(0);
        $obj_Writer = \PHPExcel_IOFactory::createWriter($excel,'Excel5');

        //设置header
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        //支持浏览器下载生成的文档 
         $all = $obj_Writer->save('php://output');//输出
        return $all;
//        die();//种植执行


//        $r = exportexcel($result,$title,$filename);
//        return $r;
    }


    /**
     * 管理员充值添加
     */
    public function admAdd($request)
    {
        if ($request->isMethod('post')) {
            $admin = Admin::where('admin_id',Session('admin_userid'))->get();
            if (md5($request['password']) != $admin[0]['password']) {
                $this->error = '管理密码错误!';
                return false;
            }
            $data['member_id'] = intval($request['member_id']);
            $member = Member::where('member_id',$data['member_id'])->get();
            if ($member->isEmpty()) {
                $this->error = '用户不存在!';
                return false;
            }
            $data['member_name'] = $member[0]['name'];
            $data['currency_id'] = intval($request['currency_id']);
            $data['money'] = $request['money'];
            $data['status'] = 1;
            $data['add_time']  = time();
            $data['type'] = 3;//管理员充值类型
            $rmb = Member::where('member_id',$data['member_id'])->first();
            $m_rmb = $rmb['rmb'] + $data['money'];
            $num = CurrencyUser::where('member_id',$data['member_id'])->first();
            $m_num = $num['num'] + $data['money'];
            DB::beginTransaction();
            try {
                DB::table('pay')->insert($data);
                if($data['currency_id'] == 0) {
                    $r[] = DB::table('member')->where('member_id',$data['member_id'])->update(['rmb' => $m_rmb]);
                }else {
                    $r[] = DB::table('currency_user')->where(['member_id' => $data['member_id'],'currency_id' => $data['currency_id']])->update(['num' => $m_num]);
                }
                $r[] = DB::table('finance')->insert(['member_id' => $data['member_id'],'type' => 3,'content' => '管理员充值','money_type' => 1,'money' => $data['money'],'currency_id' => $data['currency_id']]);
                $r[] = DB::table('message_all')->insert(['title' => '管理员充值','u_id' => $data['member_id'] ,'type'=> -2,'content' => '管理员充值'.$this->getCurrencynameByCurrency($data['currency_id']).':'.$data['money']]);
                if ($r) {
                    DB::commit();
                    $this->error = '添加成功!';
                }

            }catch (\Exception $e){
                DB::rollback();
                $this->error = '添加失败!';
//                throw $e;
            }
        }
    }



}
